from fastapi import APIRouter, HTTPException, Depends
from typing import List, Optional, Dict, Any

from app.models.prompt_template import PromptTemplate, PromptTemplateCreate, PromptTemplateUpdate, PromptTemplateUse, PromptTemplateTest, PromptTemplateTestResult
from app.services.prompt_template_service import PromptTemplateService
from app.services.ai_model_service import AIModelService

router = APIRouter()

@router.get("/prompt-templates", response_model=List[PromptTemplate])
async def get_prompt_templates(category: Optional[str] = None, tag: Optional[str] = None):
    """获取所有提示词模板，可按分类或标签筛选"""
    service = PromptTemplateService()
    return await service.get_all_templates(category, tag)

@router.get("/prompt-templates/{template_id}", response_model=PromptTemplate)
async def get_prompt_template(template_id: str):
    """获取单个提示词模板详情"""
    service = PromptTemplateService()
    template = await service.get_template_by_id(template_id)
    if not template:
        raise HTTPException(status_code=404, detail="提示词模板不存在")
    return template

@router.post("/prompt-templates", response_model=PromptTemplate)
async def create_prompt_template(template: PromptTemplateCreate):
    """创建新的提示词模板"""
    service = PromptTemplateService()
    return await service.create_template(template)

@router.put("/prompt-templates/{template_id}", response_model=PromptTemplate)
async def update_prompt_template(template_id: str, template: PromptTemplateUpdate):
    """更新提示词模板"""
    service = PromptTemplateService()
    updated_template = await service.update_template(template_id, template)
    if not updated_template:
        raise HTTPException(status_code=404, detail="提示词模板不存在")
    return updated_template

@router.delete("/prompt-templates/{template_id}")
async def delete_prompt_template(template_id: str):
    """删除提示词模板"""
    service = PromptTemplateService()
    success = await service.delete_template(template_id)
    if not success:
        raise HTTPException(status_code=404, detail="提示词模板不存在")
    return {"message": "提示词模板已删除"}

@router.post("/prompt-templates/{template_id}/process")
async def process_prompt_template(template_id: str, data: PromptTemplateUse):
    """处理提示词模板，替换变量"""
    print(f"Processing template {template_id} with data: {data}")
    service = PromptTemplateService()
    try:
        result = await service.process_template(template_id, data.variable_values)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理模板失败: {str(e)}")

@router.post("/prompt-templates/{template_id}/test", response_model=PromptTemplateTestResult)
async def test_prompt_template(template_id: str, test_data: PromptTemplateTest):
    """测试提示词模板"""
    template_service = PromptTemplateService()
    ai_service = AIModelService()
    
    # 1. 处理模板，替换变量
    try:
        processed_template = await template_service.process_template(template_id, test_data.variables)
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"处理模板失败: {str(e)}")
    
    # 2. 使用 AI 模型生成回复
    try:
        ai_response = await ai_service.generate_text(
            test_data.model_id,
            processed_template["system_prompt"],
            processed_template["user_prompt"]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"AI 生成失败: {str(e)}")
    
    # 3. 返回结果
    return {
        "processed_template": processed_template,
        "ai_response": ai_response
    } 